package cn.chiship.sdk.pay.core.util;

import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.exception.custom.BusinessException;
import cn.chiship.sdk.core.util.Base64Util;
import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.sdk.pay.core.model.PayRefundModel;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.security.PrivateKey;

/**
 * 支付工具
 *
 * @author lj
 */
public class PayUtil {

	/**
	 * 获取私钥串
	 * @param privateFile
	 * @return String
	 */
	public static String getPrivateKey(String privateFile) {
		try {
			return getPrivateKey(new FileInputStream(privateFile));
		}
		catch (FileNotFoundException e) {
			throw new BusinessException("获取私钥出错，找不到私钥文件");
		}
	}

	/**
	 * 获取私钥串
	 * @param inputStream
	 * @return String
	 */
	public static String getPrivateKey(InputStream inputStream) {
		PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(inputStream);
		return Base64Util.encode(merchantPrivateKey.getEncoded());
	}

	/**
	 * 退款各项检查
	 * @param payRefundModel
	 * @return BaseResult
	 */
	public static BaseResult checkRefund(PayRefundModel payRefundModel) {
		Double refundAmount = payRefundModel.getRefundAmount();
		Double totalAmount = payRefundModel.getTotalAmount();
		if (StringUtil.isNull(refundAmount)) {
			return BaseResult.error("退款金额不能为空");
		}
		if (StringUtil.isNull(totalAmount)) {
			return BaseResult.error("总金额不能为空");
		}
		if (refundAmount <= 0) {
			return BaseResult.error("退款金额不能小于0");
		}
		if (refundAmount > totalAmount) {
			return BaseResult.error("退款金额不能大于总金额");
		}
		if (totalAmount <= 0) {
			return BaseResult.error("总金额不能小于0");
		}
		return BaseResult.ok();
	}

}
